<template>
	<view class="five-level-address">
		<view class="picker-box">
			<text @click="openPicker(index+1)" class="item" :class="{'placeholder':index+2>currLevel}"
				v-for="(item,index) in nameList" :key="index">
				{{index < currLevel-1 ? item.name : getNextPlaceholder(index+1)}}
			</text>
			<!-- <u-icon v-if="currLevel>1" color="#999" name="close-circle" style="vertical-align: text-bottom;" size="36"
				@click="reset"></u-icon> -->
		</view>
		<u-select v-model="show" :list="list" @confirm="selectedList" :title="getNextPlaceholder(currLevel)"
			label-name="city_name" value-name="id"></u-select>
	</view>
</template>

<script>
	const nameMap = {
		'1': '省',
		'2': '市',
		'3': '县',
		'4': '乡',
		'5': '村',
	}
	import {
		getNextCity
	} from '@/api/user.js'
	export default {
		name: "five-level-address",
		data() {
			return {
				currLevel: 1,
				nameList: new Array(5).fill(null),
				list: [],
				show: false,
			};
		},
		props: {
			value: {
				default: new Array(5).fill(null)
			}
		},
		watch: {
			value: {
				immediate: true,
				handler(val) {
					if (val) {
						this.nameList = val;
						if (!val[0]) {
							this.currLevel = 1;
						}
					}
				}
			}
		},
		methods: {
			reset() {
				this.nameList = new Array(5).fill(null);
				this.currLevel = 1;
				this.$emit('input', this.nameList)
			},
			getNext(callback) {
				const id = this.currLevel == 1 ? 0 : this.nameList[this.currLevel - 2].value;
				getNextCity({
					id
				}).then(res => {
					if (res.code == 1) {
						this.list = res.msg;
						callback && callback();
					}
				})
			},
			openPicker(level, type = 0) {
				if (level > 1 && !this.nameList[level - 2]) {
					return this.$toast({
						title: '请选择' + nameMap[level - 1]
					});
				}
				this.currLevel = level;
				this.nameList.fill(null, level - 1)
				if (!type) {
					this.$emit('input', this.nameList)
				}
				this.getNext(() => {
					this.show = true;
				})
			},
			selectedList([value]) {
				this.nameList[this.currLevel - 1] = {
					name: value.label,
					value: value.value
				};
				this.$emit('input', this.nameList);
				if (this.currLevel > 5) {
					this.currLevel = 1;
				} else {
					this.currLevel++;
				}
				if (this.currLevel <= 5) {
					setTimeout(() => {
						this.openPicker(this.currLevel, 1);
					}, 200)
				}
			},
			getNextPlaceholder(i) {
				return `请选择${nameMap[i]}`
			},
		}
	}
</script>

<style lang="less">
	.five-level-address {
		background-color: #fff;
		width: 100%;
		padding: 20rpx;

		.picker-box {
			display: flex;
			row-gap: 10rpx;
			column-gap: 15rpx;
			flex-wrap: wrap;

			.item {
				line-height: 36rpx;
				border: 1rpx solid #bbb;
				padding: 0 10rpx;
				border-radius: 5rpx;
			}

			.placeholder {
				color: #aaa;
			}
		}
	}
</style>